<?php
class CategoryController extends CommonController{
    private $model;
    public function __init(){
        parent::__init();
        $this->model = K('Category');
    }
    // 首页
    public function index(){
        $data = $this->model->get_data();
        $data= Data::tree($data,'cname','cid','pid');
        $this->assign('data',$data);
        $this->display();
    }
    // 添加分类
    public function add_cate(){
        if(IS_POST){
            if ($this->model->create()){
                $this->model->add_data();
                $this->success('添加成功',U('index'));
            }
            $this->error($this->model->error);
        }
        $this->display();
    }
    // 编辑
    public function edit_cate(){
        if(IS_POST){
            $cid=Q('post.cid',0,'intval');
            $this->model->update_data(array('cid'=>$cid));
            $this->success('修改成功',U('index'));
        }
        $cid=Q('get.cid',0,'intval');
        $oldData=$this->model->get_one_data(array('cid'=>$cid));
        $this->assign('oldData', $oldData);
        // p($oldData);die;
        $cateData = $this->model->get_data();   
        $this->assign('cateData',$cateData);
        $this->display();
    }
    // 添加子分类
    public function add_son(){
        if(IS_POST){
            // p($_POST);die;
            if($this->model->create()){
                $this->model->add_data();
                $this->success('添加成功',U('index'));
            }
            $this->error($this->model->error);
        }
        $data=$this->model->get_one_data(array('cid'=>Q('get.cid',0,'intval')));
        $this->assign('fatherCate',$data);
        $this->display();
    }
    // 删除
    public function del(){
        if($this->model->del_data(Q('get.cid',0,'intval'))){
            $this->success('删除成功');
        }else{
            $this->error($this->model->error);
        }
    }
    // 异步静态切换
    public function ajax_change_stat(){
        if(!IS_AJAX) $this->error('非法请求');
        $this->model->change_stat();
        $arr = array(
            'status' => 1,
            'message'=>'修改成功',
        );
        $this->ajax($arr);      
    }
    // 异步显隐切换
    public function ajax_get_sonid(){
        if(!IS_AJAX) $this->error('非法请求');
        $data=$this->model->get_data();
        $data_son=$this->model->get_data_son($data,Q('post.cid',0,'intval'));
        $this->ajax($data_son);
    }
}
